package service;

import java.util.Arrays;

/**
 * Created by fanzhenyu02 on 2020/7/15.
 */
public class BinarySearchService {


    public int binarySearch(int[] arr, int target) {
        if (null == arr || arr.length <= 0) {
            return -1;// -1 indicates that the array is invalid.
        }

        int left = 0, right = arr.length - 1, mid;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                return mid;
            }

            if (arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }

        // default return -1;
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1};// first, is any require to the input ?
        // shall the array be sorted ?
        // if not sorted, it shall be sorted first.
        Arrays.sort(arr);// assume it is not sorted.
        BinarySearchService an = new BinarySearchService();
        System.out.println(an.binarySearch(arr, 1));
    }


}
